package com.platform.modules.quality.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import com.platform.modules.sys.entity.SysOrgEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysUserRoleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.page.PageUtil;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.StringUtils;
import com.platform.modules.sys.controller.AbstractController;
import com.platform.util.DocUtil;
import com.platform.modules.quality.service.QlyInspectionService;
import com.platform.web.utils.CommonResult;
import com.platform.modules.quality.vo.QlyInspectionStatusQuantityByAppVo;
import com.platform.modules.quality.dto.QlyInspectionListByAppDto;
import com.platform.modules.quality.dto.QlyInspectionStatusQuantityByAppDto;
import com.platform.modules.quality.entity.QlyAcceptanceEntity;
import com.platform.modules.quality.entity.QlyInspectionEntity;
import com.platform.modules.quality.entity.QlyInspectionItemEntity;
import com.platform.modules.quality.service.QlyInspectionItemService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * Controller
 *
 * @author Zhouxw
 * @date 2019-06-20 17:17:28
 */
@Api(tags = "QlyInspectionController|質量巡查")
@RestController
@RequestMapping("qly/inspection")
public class QlyInspectionController extends AbstractController {

    @Autowired
    private QlyInspectionService qlyInspectionService;
    @Autowired
    private QlyInspectionItemService qlyInspectionItemService;
    @Autowired
    private DocUtil docUtil;
    @Autowired
	SysUserRoleService sysUserRoleService;

    
    /**
     * @descr 查询 质量巡查记录，只查询自己创建的质量存查记录，不考虑其他数据范围<br>
     * @param currPage
     * @param limit
     * @return
     */
    @ApiOperation(value = "查询 质量巡查记录PC")
    @PostMapping("/list")
    public RestResponse query(Integer currPage, Integer limit, @RequestParam(required = false) String prjName, 
    		@RequestParam(required = false) String cityNum, @RequestParam(required = false) String countyNum, 
    		@RequestParam(required = false) String sgCorpName, @RequestParam(required = false) String buildCorpName,
    		@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate,
    		@RequestParam(required = false) String[] queStatus) {
    	Map<String, Object> params = new HashMap<>();
//    	params.put("userId", getUserId());
//        params.put("page", PageUtil.getCurrPage(currPage));
//        params.put("limit", PageUtil.getLimit(limit));
//        params.put("cityNum", cityNum);
//        params.put("countyNum", countyNum);
//        params.put("prjName", prjName);
//        params.put("sgCorpName", sgCorpName);
//        params.put("buildCorpName", buildCorpName);
//        params.put("startDate", startDate);
//        params.put("endDate", endDate);
//        params.put("queStatus", queStatus);




        params.put("page", PageUtil.getCurrPage(currPage));
        params.put("limit", PageUtil.getLimit(limit));
        params.put("prjName", prjName);
        params.put("sgCorpName", sgCorpName);
        params.put("buildCorpName", buildCorpName);
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("queStatus", queStatus);

        SysOrgEntity orgEntity = getOrg();
        // 当前是项目组织
        if(orgEntity == null){
            params.put("prjId", getOrgNo());
        }else{ // 实体组织
            // 如果是监管机构
            if("5".equals(orgEntity.getOrgType())){
                if(orgEntity.getOrgLevel()==2){
                    params.put("provinceNum", orgEntity.getProvinceNo());
                    params.put("countyNum", countyNum);
                    params.put("cityNum", cityNum);
                }else if(orgEntity.getOrgLevel()==3){
                    params.put("cityNum", orgEntity.getCityNo());
                    params.put("countyNum", countyNum);
                }else if(orgEntity.getOrgLevel()==4){
                    params.put("countyNum", orgEntity.getCountyNo());
                }
            }else if ("1".equals(orgEntity.getOrgType())){
                params.put("buildCorpId", getOrgNo());
            }else if ("9".equals(orgEntity.getOrgType())){
                params.put("sgCorpId", getOrgNo());
            }
        }



    	Page<QlyInspectionEntity> page = qlyInspectionService.queryPage(params);
        return RestResponse.success().put("page", page);
    } 
    
    
    @ApiOperation(value = "图纸分析 PC/APP", notes = "图纸分析 PC/APP")
    @PostMapping("/drawing/analysis")
    public CommonResult<List<QlyInspectionEntity>> drawingAnalysis(
    		@RequestParam(required = true) String attId) {
    	Map<String, Object> params = new HashMap<>();
    	params.put("attId", attId);
    	List<QlyInspectionEntity> list = qlyInspectionService.queryList(params);
    	
    	
    	//计算数量
    	Map<String,Object> extra = new HashMap<>(4);
    	extra.put("1",0);
    	extra.put("2",0);
    	extra.put("3",0);
    	extra.put("4",0);
    	list.forEach(e->{
    		if(StringUtils.isNotBlank(e.getQueStatus())) {
    			int num = (int) extra.get(e.getQueStatus());
        		extra.put(e.getQueStatus(),++num);
    		}
    	});
        return CommonResult.success(list).putAll(extra);
    } 
    
    
    
    @ApiOperation(value = "查询 质量巡查记录PC")
    @PostMapping("/page")
    @Deprecated
    public RestResponse page(@RequestParam(required = false) String attId) {
    	Map<String, Object> params = getParams();
    	params.put("attId", attId);
    	IPage<QlyInspectionEntity> page = qlyInspectionService.queryPage(params);
    	return RestResponse.success().put("page", page);
    } 
    
    
    
    /**
     * @descr 查询 质量巡查记录 app<br>
     * @param currPage
     * @param limit
     * @return
     */
    @ApiOperation(value = "查询 质量巡查记录APP")
    @PostMapping("/listByAPP")
    public RestResponse listByAPP(@Valid @RequestBody QlyInspectionListByAppDto queryDto) {
    	SysUserEntity user = getUser();
    	SysOrgEntity org = getOrg();
    	
    	Map<String, Object> params = new HashMap<>();
        params.put("page", PageUtil.getCurrPage(queryDto.getCurrPage()));
        params.put("limit", PageUtil.getLimit(queryDto.getLimit()));
        params.put("prjId", queryDto.getPrjId());
        params.put("responsibleUserId", queryDto.getResponsibleUserId());
        params.put("queStatus", queryDto.getQueStatus());
    	//有工区负责人, 表示项目组织查询
        if(null!=queryDto.getResponsibleUserId()) {
        	//判断工区负责人参数responsibleUserId是否是项目经理
        	List<String> roleList = sysUserRoleService.queryRoleIdList(queryDto.getResponsibleUserId());
        	if(roleList.contains("ROLE_PM")) {
        		//项目经理查询全部,删除工区负责人条件
        		params.remove("responsibleUserId");
        	}
        }else {
        	//没有工区负责人, 表示非项目组织查询, 判断要不要增加CREATE_USER_ID条件
        	if(null!=user) {
            	//判断当前登录用户 是否是机构组织负责人(也有可能改成判断数据权限)
            	List<String> roleList = sysUserRoleService.queryRoleIdList(user.getUserId());
            	if(!roleList.contains("JGDWGLY")) {
            		params.put("createUserId", user.getUserId());
            	}
        	}else {
        		logger.error("未找到当前登录用户");
        	}
        }
        
    	Page<QlyInspectionEntity> page = qlyInspectionService.queryPageByApp(params);
        return RestResponse.success().put("page", page);
    } 
    
    /**
     * @descr 查询 质量巡查记录的问题列表<br>
     * @param currPage
     * @param limit
     * @return
     */
    @ApiOperation(value = "查询 质量巡查记录的问题列表")
    @PostMapping("/inspectionItemList")
    public RestResponse inspectionItemList(@RequestParam String insId) {
    	List<QlyInspectionItemEntity> list = qlyInspectionItemService.queryInspectionItemList(insId);
        return RestResponse.success().put("data", list);
    } 
    
    /**
     * @descr 查询 质量巡查记录的问题列表 及整改信息<br>
     * @param currPage
     * @param limit
     * @return
     */
    @ApiOperation(value = "查询 质量巡查记录的问题及整改列表")
    @PostMapping("/inspectionItemAndReformList")
    public RestResponse inspectionItemAndReformList(@RequestParam String insId) {
    	List<QlyInspectionItemEntity> list = qlyInspectionItemService.queryInspectionItemAndReformList(insId);
        return RestResponse.success().put("data", list);
    } 
    
    /**
     * @descr 保存/修改 质量巡查记录<br>
     * @param qlyInspectionEntity
     * @return
     */
    @ApiOperation(value = "保存/修改 - 质量巡查记录")
    @PostMapping("save")
    public RestResponse save(@RequestBody QlyInspectionEntity qlyInspectionEntity) {
    	boolean b = qlyInspectionService.saveOrUpdate(qlyInspectionEntity);
    	if(b) {
    		//推送质量巡查记录通知
    		qlyInspectionService.sendMessage(qlyInspectionEntity);
    	}
        return RestResponse.success().put("data", qlyInspectionEntity);
    }
    

    @ApiOperation(value = "保存/修改 - 质量巡查问题记录")
    @PostMapping("/item/save")
    public RestResponse saveItem(@RequestBody QlyInspectionItemEntity qlyInspectionItemEntity) {
    	qlyInspectionItemService.saveOrUpdate(qlyInspectionItemEntity);
        return RestResponse.success().put("data", qlyInspectionItemEntity);
    }
   
    
    @ApiOperation(value = "上传 - 质量巡查问题图片")
    @PostMapping("/item/pic")
    public RestResponse saveItemPic(MultipartFile file, String insItemId) {
    	docUtil.createAtt(file, "", insItemId);
        return RestResponse.success();
    }
    
    
    @ApiOperation(value = "查询 - 质量巡查问题图片附件列表")
    @GetMapping("/item/pic")
    public RestResponse getItemPic(String insItemId) {
        return RestResponse.success().put("list", docUtil.getAttListByAttBusinessId(insItemId));
    }
    
    
    @ApiOperation(value = "删除 - 质量巡查问题图片")
    @DeleteMapping("/item/pic")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "delete", name = "attIds", value = "文件id(支持多个,逗号分割)", dataType = "String")
    })
    public RestResponse deleteItemPic(String attIds) {
    	if(StringUtils.isNotBlank(attIds)) {
    		docUtil.deleteAtts(Arrays.asList(attIds.split(",")));
    	}
        return RestResponse.success();
    }

    @GetMapping("/overdue")
    public RestResponse overdue() {
    	qlyInspectionService.overdue(null);
        return RestResponse.success();
    }
    
    /**
     * @descr 质量巡查状态统计APP
     * @return
     */
    @ApiOperation(value = "质量巡查状态统计(状态数量)APP")
    @PostMapping("/statusQuantity")
    public CommonResult<QlyInspectionStatusQuantityByAppVo> statusQuantity(@Valid @RequestBody QlyInspectionStatusQuantityByAppDto statusQuantityDto) {
        QlyInspectionStatusQuantityByAppVo statusQuantity = qlyInspectionService.statusQuantity(statusQuantityDto.getPrjId());
        return CommonResult.success(statusQuantity);
    } 
    
    
}
